<template>
	<view>
		<view class="search-box">
			<uni-search-bar @input="input" cancelButton focus placeholder="请输入搜索内容" radius="100"></uni-search-bar>
		</view>
		<view class="sugg-list" v-if="searchResults.length">
			<view class="sugg-item" v-for="item in searchResults" :key="item.goods_id" @click="gotoDetail(item.goods_id)">
				<text class="name">{{item.goods_name}}</text>
				<uni-icons type="forward"></uni-icons>
			</view>
		</view>
		<view class="history-box" v-else>
			<view class="history-title">
				<text>搜索历史</text>
				<uni-icons type="trash-filled" @click="delHistory"></uni-icons>
			</view>
			<view class="history-list">
				<uni-tag @click="gotoGoodsList(item)" type="lightGray" :text="item" v-for="(item,index) in histories" :key="index"/>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				timer: '',
				searchResults: [],
				historyList: JSON.parse(uni.getStorageSync('searchHistory') || '[]'),
				keywords: ''
			}
		},
		methods: {
			input(value){
				clearTimeout(this.timer)
				this.timer = setTimeout(()=>{
					this.keywords = value
					this.getSearchList()
				},500)
			},
			async getSearchList(){
				if(!this.keywords) {
					this.searchResults = []
					return
				}
				const { data } = await uni.$http.get("/goods/qsearch?query="+this.keywords, { isLoading: false })
				if(data.meta.status !== 200) return uni.$showMsg()
				this.searchResults = data.message
			},
			gotoDetail(id){
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?id='+ id
				})
				this.saveSearchHistory()
			},
			saveSearchHistory(){
				this.historyList = this.historyList.filter(item => item !== this.keywords )
				this.historyList.push(this.keywords)
				uni.setStorageSync('searchHistory',JSON.stringify(this.historyList))
			},
			delHistory(){
				this.historyList = []
				uni.setStorageSync('searchHistory','[]')
			},
			gotoGoodsList(keyword){
				uni.navigateTo({
					url: '/subpkg/goods_list/goods_list?query=' + keyword
				})
			}
		},
		computed: {
			histories() {
				return [...this.historyList].reverse()
			}
		}
	}
</script>

<style lang="scss">
.search-box{
	position: sticky;
	top: 0;
	z-index: 999;
}
.sugg-list{
	padding: 0 5px;
	.sugg-item{
		display: flex;
		justify-content: space-between;
		font-size: 12px;
		padding: 13px 0;
		border-bottom: 1px solid #efefef;
		.name{
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			margin-right: 3px;
		}
	}
}
.history-box{
	padding: 5px;
	.history-title{
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 40px;
		font-size: 13px;
		border-bottom: 1px solid #efefef;
	}
	.history-list{
		display: flex;
		flex-wrap: wrap;
		uni-tag{
			margin: 5px;
		}
	}
}
</style>
